<template>
  <view>
    <uni-nav-bar title="接受邀请" color="#333" :border="false" statusBar></uni-nav-bar>
    <image :src="CreateImg" mode="widthFix" class="acceptImg"></image>
    <!-- 头部邀请信息 -->
    <view class="accept">
      <view class="accept_name">{{fromNmae.realname?fromNmae.realname:fromNmae.nickname}}邀请您加入</view>
      <view class="accept_name">{{teamInfo.name}}</view>
      <view class="images">
        <view class="image_list" v-if="teamInfo.driver_avatar">
          <image v-for="(item,index) in teamInfo.driver_avatar" :key="index" :src="item.avatar" mode=""></image>
          <text>{{teamInfo.driver_count}}人</text>
        </view>
      </view>
      <view class="detail_huanb">
        <text>环保分：</text>
        <text>{{teamInfo.score}}</text>
      </view>
    </view>
    <!-- 团队等级 -->
    <GradeList :type="'super'" :teamInfo="teamInfo" :show="false"></GradeList>
    <view class="phones_tel">
      <text style="font-size: 30rpx">手机号</text>
      <input type="number" :placeholder="userinfo.mobile ? userinfo.mobile : '请输入手机号码'" maxlength="11" v-model="phone"
        style="width: 80%" :disabled="userinfo.mobile ? true : false" />
    </view>
    <view class="phones_tel" v-if="!userinfo.mobile">
      <text style="font-size: 30rpx">验证码</text>
      <view class="phones_code">
        <input v-model="code" style="width: 50%" placeholder="请输入验证码" type="number" maxlength="4" />
        <view class="_code" @click="handleCodeClick('100')">{{ textArea }}</view>
      </view>
    </view>
    <view class="AcceptInvitation" @click="submit(1)">接受邀请</view>
    <!-- 浮窗按钮 -->
    <drag-button :isDock="true" :existTabBar="true" @btnClick="JumpTab" @btnTouchstart="btnTouchstart"
      @btnTouchend="btnTouchend" />
    <!-- <view class="AcceptBottom">
      <view class="">
        您如果想加入该团，请
        <text @click="submit(2)">点击这里</text>
      </view>
      <view class="">退出已经加入任一车友团{$可选为0显示}</view>
    </view> -->
    <view class="bot"></view>
    <Lotlats @position="position"></Lotlats>
  </view>
</template>

<script setup lang="ts">
  import GradeList from '@c/team/Grade.vue';
  import Lotlats from '@c/team/Lotlat.vue';
  import dragButton from '@/components/drag-button/drag-button.vue';
  import { showLoading, showToast, successToast, errorToast } from '@/utils/prompt';
  import { ref, Ref } from 'vue';
  import { toPublish } from '@mqtt';
  import { Creategroup, GetCities, getdriver } from '@/gql/team';
  import { useUserStore } from '@/stores/user';
  import { getDriverID } from '@/stores/driverID';
  import { onLoad } from '@dcloudio/uni-app';
  import { decrypt } from '@/utils/jsencrypt';
  import { userInfo } from '@/gql/user';
  const driver_id = getDriverID();
  const userinfo = useUserStore();
  const teamInfo : Ref<any> = ref({});
  const fromNmae : Ref<any> = ref({});
  const phone = ref('');
  const code = ref('');
  const textArea = ref('验证码');
  const btnBool = ref(true); //放重复点击
  const CreateImg = ref('');
  const fromDriverId = ref('');
  const teamId = ref('');
  const key = ref('');
  const region = ref('')
  const repeat = ref(true); //放重复点击
  const all = ref()
  const user_id = ref()
  onLoad((pearm) => {
    if (!uni.getStorageSync('storage_key').id || !driver_id) {
      uni.setStorageSync('storage', 'user');
      uni.reLaunch({
        url: '/pages/login/login',
      });
      return;
    }
    user_id.value = Number(pearm.driver_id)
    const loct = uni.getStorageSync('StoreData')
    all.value = JSON.parse(decrypt(loct))
    fromDriverId.value = all.value.from_driver_id;
    teamId.value = all.value.team_id;
    region.value = all.value.region;
    key.value = all.value.key
    Creategroups();
    setTimeout(() => {
      getUserInfo();
    }, 1000);
  });
  /**
   * 获取顶部图片
   */
  function Creategroups() {
    const payload = {
      query: Creategroup,
      variables: { type: 'team_yq_sup' },
    };
    toPublish('ql/team/getAds', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      CreateImg.value = data.get_ads.imageurl;
    });
  }

  //获取邀请人信息
  function getUserInfo() {
    const payload = {
      query: userInfo,
      variables: { driver_id: Number(fromDriverId.value) },
    };
    toPublish('ql/driver/getDriverInfo', payload, (obj : any) => {
      const { data } = obj;
      fromNmae.value = data.driver_info;
    });
  }

  /**
   * 获取当前城市信息
   * @param {Object} lat 当前位置的纬度
   * @param {Object} lot 当前位置的经度
   */
  function position(lat : number, lot : number) {
    showLoading('正在加载');
    const payload = {
      query: GetCities,
      variables: {
        lon: lot,
        lat: lat,
      },
    };
    toPublish('ql/team/getCity', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      getdrivers(data.get_city.code);
    });
  }
  /**
   * @param {Object} code 城市code
   * 获取团队信息
   */
  function getdrivers(code : string) {
    const payload = {
      query: getdriver,
      variables: {
        code,
        team_id: Number(teamId.value),
      },
    };
    toPublish('ql/team/getTeamInfo', payload, (obj : any) => {
      uni.hideLoading();
      const { data } = obj;
      teamInfo.value = data.get_team_info;
    });
  }

  /**
   * 正则手机号码
   */
  function phoneTel() {
    const mobile = /^1[3-9]\d{9}$/;
    const userPhone = userinfo && userinfo.mobile ? userinfo.mobile : phone.value;
    return mobile.test(userPhone);
  }

  /**
   * 发送验证码
   */
  function handleCodeClick() {
    if (!phone.value) {
      showToast('手机号不能为空');
      return;
    } else if (!phoneTel()) {
      showToast('请输入正确的手机号码');
      return;
    }
    if (btnBool.value) {
      btnBool.value = false;
      const payload = {
        event: 'notice',
        mobile: phone.value,
      };
      toPublish('driver/sendSms', payload, (obj : any) => {
        console.log(obj);
      });
      successToast('发送成功');
      let i = 60;
      let timer = setInterval(() => {
        textArea.value = +i + 's';
        i--;
        if (i < 0) {
          btnBool.value = true;
          textArea.value = '验证码';
          clearInterval(timer);
        }
      }, 1000);
    } else {
      return;
    }
  }
  /**
   * @param {Object} num 1 接收团邀请 2 返回团首页
   */
  function submit(num: number) {
    tieUp()
    switch (num) {
      case 1:
        const mobile = phone.value ? phone.value : userinfo.mobile;
        if (!mobile) {
          showToast('请填写完整信息');
          return;
        } else if (!phoneTel()) {
          showToast('请输入正确的手机号码');
          return;
        } else if (phone.value && !code.value) {
          showToast('请输入验证码');
          return;
        }
        submit_s(mobile);
        break;
      case 2:
        uni.redirectTo({
          url: '/pages/index/teamIndex',
        });
        break;
    }
  }
  /**
   * @param {Object} mobile 手机号码
   */
  function submit_s(mobile) {
    if (!teamInfo.value) {
      return;
    }
    showLoading()
    if (!repeat.value) {
      return;
    }
    repeat.value = false;
    const payload = {
      team_id: Number(teamId.value),
      driver_id,
      mobile,
      code: code.value,
      parent_id: Number(fromDriverId.value),
    };
    toPublish('team/confirmInvite', payload, (obj : any) => {
      uni.hideLoading();
      const { code, msg } = obj;
      if (code === 1) {
        successToast(msg);
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/index/teamIndex',
          });
        }, 1000);
      } else {
        repeat.value = true;
        errorToast(msg);
      }
    });
  }
  //绑定身份
  function tieUp() {
    if (!key.value) {
      return
    }
    const payload = {
      zhitui_id: Number(fromDriverId.value),
      key: key.value,
      region_id: Number(region.value),
      driver_id: user_id.value ? user_id.value : driver_id
    };
    toPublish('driver/bind', payload, (obj : any) => { });
  }
  function JumpTab() {
    uni.redirectTo({
      url: '/pages/index/filling',
    });
  }
</script>

<style scoped lang="less">
  @import url('../team/less/accept.less');
</style>
<style>
  page {
    background-color: #fff;
  }

  body {
    background-color: #fff;
    height: 100vh;
    overflow: auto;
    font-family: 'PingFangSC-Regular', 'PingFang SC';
  }
</style>